import cgi
import math
import logging
import random
from ovzdusi_entities import *
from datetime import datetime, timedelta
from google.appengine.ext import webapp, db
from google.appengine.ext.webapp import util


class GenerateMeasurePoint(webapp.RequestHandler):
    res = """
        <html>
        <body>
          <form action="#" method="post">
            <div>code: <input type="text" name="code" /></div>
            <div>name: <input type="text" name="name" /></div>
            <div><input type="submit" value="Generate" /></div>
          </form>
        </body>
        </html>"""

    def get(self):
        self.response.out.write(self.res)

    def post(self):
        code = cgi.escape(self.request.get('code'))
        name = cgi.escape(self.request.get('name'))
        mp = MeasurePoint(code = code, name = name)
        mp.put()
        self.response.out.write(self.res)


class GeneratePollution(webapp.RequestHandler):
    res = """
        <html>
        <body>
          <form action="#" method="post">
            <div>date: <input type="text" name="date" /></div>
            <div>PM10: <input type="text" name="pm10" /></div>
            <div>MP: <select name="mpcode">
                %s
            </select></div>
            <div><input type="submit" value="Generate" /></div>
          </form>
        </body>
        </html>"""

    def get_options(self):
        options = ""
        query = db.GqlQuery("select * from MeasurePoint")
        for mp in query.fetch(1000):
            options += "<option value=\"%(c)s\">%(n)s</option>" % {"c":mp.code, "n":mp.name}
        return options
    
    def get(self):
        self.response.out.write(self.res % self.get_options())
        
    def post(self):
        mpcode = self.request.get('mpcode')
        query = db.GqlQuery("select * from MeasurePoint where code = :1", mpcode)
        mp = query.fetch(1)[0]
        date = datetime.strptime(self.request.get('date'), "%Y-%m-%d %H:%M")
        pm10 = float(self.request.get('pm10'))
        p = Pollution(date = date, PM10 = pm10, measurePoint = mp)
        p.put()
        self.response.out.write(self.res % self.get_options())


class GenerateRndPollution(webapp.RequestHandler):
    def get(self):
        req_days = self.request.get('days')
        if req_days is None or len(req_days) == 0:
            return

        d = int(req_days)
        now = datetime.now()
        startDate = now - timedelta(d)
        query = db.GqlQuery("select * from Pollution where date > :1 order by date desc", startDate)
        max = query.fetch(1)
        if max is not None and len(max) > 0:
            startDate = max[0].date + timedelta(hours = 1)
        diff = now - startDate
        hours = int(math.floor((diff.days * 3600 * 24 + diff.seconds) / 3600))
        query = db.GqlQuery("select * from MeasurePoint")
        mps = query.fetch(100)
        nowHour = datetime(now.year, now.month, now.day, now.hour)
        for i in range(hours):
            for mp in mps:
                if i == 2: # simulating missing value for all MPs
                    break;
                if i == 10 and mp.name == 'Ostrava-Fifejdy': # simulating missing value for one particular MP
                    break;
                p = Pollution(date = nowHour - timedelta(hours = i), PM10 = float(random.randint(0, 150)), measurePoint = mp)
                p.put()

def main():
    logging.getLogger().setLevel(logging.DEBUG)
    application = webapp.WSGIApplication([
        ('/generate-measurepoint', GenerateMeasurePoint),
        ('/generate-pollution', GeneratePollution),
        ('/generate-pollution-rnd', GenerateRndPollution)
        ], debug=True)
    util.run_wsgi_app(application)


if __name__ == '__main__':
    main()
